package com.test.demo.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * sharding-jdbc数据
 * @author
 */
@Configuration
public class ShardingDataSourceConfig {

    @Value("${sharding.jdbc.data-source.type}")
    private Class<? extends DataSource> dataSourceType;

    @Value("${sharding.db0.name}")
    private String db0Name;

    @Value("${sharding.db1.name}")
    private String db1Name;

    @Bean
    @Primary
    @ConfigurationProperties(prefix = "sharding.jdbc.data-source.sharding-db0")
    public DataSource shardingDataSource0() {
        DataSource build = DataSourceBuilder.create().type(dataSourceType).build();
        return build;
    }

    @Bean
    @ConfigurationProperties(prefix = "sharding.jdbc.data-source.sharding-db1")
    public DataSource shardingDataSource1() {
        return DataSourceBuilder.create().type(dataSourceType).build();
    }

    @Bean(name = "allShardingDataSource")
    public Map<String, DataSource> allShardingDataSource() {
        Map<String, DataSource> dataSourceMap = new HashMap<>(2);
        dataSourceMap.put(db0Name, shardingDataSource0());
        dataSourceMap.put(db1Name, shardingDataSource1());
        return dataSourceMap;
    }
}

